<template>
  <a-card :bordered="false" style="height: 100%;">
    <a-spin :spinning="loading">
      <a-tree
        showLine
        checkable
        checkStrictly
        :expandedKeys.sync="expandedKeys"
        :selectedKeys="selectedKeys"
        :treeData="treeDataSource"
        :checkedKeys="checkedKeys"
        @check="handleTreeCheck"
        @select="handleTreeSelect"
      />
    </a-spin>

    <a-modal
      :maskClosable="false"
      :keyboard="false"
      :title="customFunc_title"
      :width="customFunc_width"
      :visible="customFunc_visible"
      @ok="customFunc_handleOk"
      @cancel="customFunc_handleCancel"
      :cancelText="$t('m.common.button.close')">
      <a-form layout="inline">
        <a-form-item :label="$t('m.bpm.design.relation_customclass_label')" :labelCol="labelCol" :wrapperCol="wrapperCol" style="width: 100%">
          <a-input v-model="customFunc.name" :placeholder="$t('m.bpm.design.relation_customclass_placeholder')"/>
        </a-form-item>
      </a-form>
      <!--需要实现的接口是com.yuncheng.bpm.core.delegate.CustomFuncInterFace-->
    </a-modal>

    <ych-modal
      :fullscreen="false"
      size="middle"
      :title="variable_title"
      :visible="variable_visible"
      @ok="variable_handleOk"
      @cancel="variable_handleCancel"
      :cancelText="$t('m.common.button.close')">
      <a-form layout="inline">
        <a-form-item :label="$t('m.bpm.other.showVariable')" :labelCol="labelCol" :wrapperCol="wrapperCol" style="width: 100%">
          <variableTag v-model="variable.name" :placeholder="$t('m.bpm.other.showVariable_placeholder')"/>
        </a-form-item>
        <a-form-item :label="$t('m.bpm.entity.varType')" :labelCol="labelCol" :wrapperCol="wrapperCol" style="width: 100%">
          <a-select v-model="variable_type" :placeholder="$t('m.bpm.other.showVariable_select_placeholder')">
            <a-select-option value="user">{{$t('m.bpm.design.select_user_tab_name_user')}}</a-select-option>
            <a-select-option value="dept">{{$t('m.bpm.design.select_user_tab_name_dept')}}</a-select-option>
            <a-select-option value="role">{{$t('m.bpm.design.select_user_tab_name_role')}}</a-select-option>
            <a-select-option value="position">{{$t('m.bpm.design.select_user_tab_name_position')}}</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>

      <select-relation-position-list ref="selectRelationPositionList" :radio="true" v-if="variable_visible && variable_type === 'dept'"></select-relation-position-list>
    </ych-modal>

    <open-script-dialog ref="actionScriptDialog" @selectFinished="selectActionScriptFinished" @cancel="cancelScript" help-code="customProcessActorForGroovy" :groovy="true"></open-script-dialog>
  </a-card>
</template>

<script>

  import { getAction } from '@/api/manage'
  import YchConstant from '@/api/YchConstant'
  import variableTag from './variableTag/index'
  import SelectRelationPositionList from "./SelectRelationPositionList";
  import OpenScriptDialog from "../../../eform/modules/actAppView/OpenScriptDialog";

  export default {
    name: 'SelectRelationTree',
    props: {
      value: {
        type: Array,
        required: true
      }
    },
    components:{
      variableTag,
      SelectRelationPositionList,
      OpenScriptDialog,
    },
    data() {
      return {
        loading: false,
        treeDataSource: [],
        expandedKeys: [],
        selectedKeys: [],
        relationPositionIds: [
          'currentUserDept',
          'currentUserTopOneDept',
          'currentUserTopTwoDept',
          'currentUserTopMaxDept',
          'currentUserOrgRole',
          'currentUserSameLevelOrgRole',
          'currentUserTopOneOrgRole',
          'currentUserTopTwoOrgRole',
          'currentUserDeptRole',
          'firstUserDept',
          'firstUserTopOneDept',
          'firstUserTopTwoDept',
          'firstUserTopMaxDept'
        ],
        url: {
          list: YchConstant.PREFIX_BPM + '/bpm-back/processSelectRest/queryRelationTreeList/v1'
        },
        labelCol: {
          span: 6
        },
        wrapperCol: {
          span: 18
        },
        customFunc_title: this.$t('m.bpm.design.relation_customclass_title'),
        customFunc_width: 500,
        customFunc_visible: false,
        customFunc: {},
        variable_title: this.$t('m.bpm.design.relation_variable_title'),
        variable_visible: false,
        variable: {},
        variable_type: 'user'
      }
    },
    created() {
      this.queryTreeData()
    },
    computed: {
      checkedKeys() {
        const data = []
        this.value.forEach(item => {
          if (item.id.indexOf('#') != -1) {
            const parentId = item.id.substring(0, item.id.indexOf('#'))
            if (data.indexOf(parentId) == -1) {
              data.push(parentId)
            }
          } else {
            data.push(item.id)
          }
        })
        return {
          checked: data
        }
      }
    },
    methods: {
      queryTreeData() {
        this.commonRequestThen(getAction(this.url.list))
      },
      handleTreeSelect(selectedKeys, event) {
        this.selectedKeys = selectedKeys
        const title = event.node.dataRef.title
        const value = event.node.dataRef.value
        if (this.relationPositionIds.indexOf(value) != -1) {
          this.$emit('setCurrentRelation', value, title)
        } else {
          this.$emit('setCurrentRelation', null, null)
        }
      },
      handleTreeCheck(checkedKeys, e) {
        const oldKeys = this.checkedKeys.checked
        const data = this.value.filter(item => {
          let id = item.id
          if (id.indexOf('#') != -1) {
            id = id.substring(0, id.indexOf('#'))
          }
          return checkedKeys.checked.indexOf(id) != -1
        })//原来剩下的
        const addIds = checkedKeys.checked.filter(id => oldKeys.indexOf(id) == -1)//新增的
        e.checkedNodes.forEach(item => {
          if (addIds.indexOf(item.data.props.value) != -1) {
            const checkedData = {
              id: item.data.props.value,
              name: item.data.props.title
            }
            data.push(checkedData)
            // 自定义实现类选人
            if (checkedData.id === 'customFunc') {
              this.customFunc = checkedData
              this.customFunc.name = ''
              this.customFunc_visible = true
            } else if (checkedData.id === 'variable') {
              this.variable = checkedData
              this.variable.name = ''
              this.variable_type = 'user'
              this.variable_visible = true
            } else if (checkedData.id === 'customGroovy') {
              checkedData.script = ''
              this.$refs.actionScriptDialog.open('')
            }
          }
        })
        this.$emit('input', data)

        //默认选中事件
        if (addIds.length > 0) {
          const selectedNode = this.treeDataSource.find(vo => vo.key == addIds[0])
          this.selectedKeys = [selectedNode.key]
          if (this.relationPositionIds.indexOf(selectedNode.key) != -1) {
            this.$emit('setCurrentRelation', selectedNode.key, selectedNode.title)
          } else {
            this.$emit('setCurrentRelation', null, null)
          }
        } else {
          this.selectedKeys = []
          this.$emit('setCurrentRelation', null, null)
        }
      },
      selectActionScriptFinished(script) {
        if (script) {
          this.value.find(item => item.id === 'customGroovy')['script'] = script;
        } else {
          this.cancelScript();
        }
      },
      cancelScript() {
        const data = this.value.filter(vo => vo.id !== 'customGroovy')
        this.$emit('input', data)
      },
      commonRequestThen(promise) {
        this.loading = true
        promise.then(res => {
          if (res.success) {
            this.treeDataSource = res.result
            // 默认选中第一条数据、默认展开所有第一级
            if (this.treeDataSource.length > 0) {
              this.expandedKeys = res.result.map(item => item.key)
            } else {
              this.expandedKeys = []
            }
          } else {
            this.messageUtil.warning(this.$t('m.bpm.verify.tip_relation_query_fail')+'：' + res.message)
            console.error(res)
          }
        }).finally(() => {
          this.loading = false
        })
      },
      customFunc_handleOk() {
        if (this.customFunc.name) {
          this.customFunc.name = this.$t('m.bpm.design.relation_customclass_label')+'#' + this.customFunc.name
        }
        this.customFunc_close()
      },
      customFunc_handleCancel() {
        this.customFunc.name = null
        this.customFunc_close()
      },
      customFunc_close() {
        this.customFunc_visible = false
        if (!this.customFunc.name) {
          const data = this.value.filter(vo => vo.id != 'customFunc')
          this.$emit('input', data)
        }
      },
      variable_handleOk() {
        if (this.variable_type === 'dept') {
          if (this.$refs.selectRelationPositionList.selectionRows.length === 0) {
            this.variable_handleOkToSet();
          } else {
            const position = this.$refs.selectRelationPositionList.selectionRows[0];
            this.variable_handleOkToSet(position.name, position.id);
          }
        } else {
          this.variable_handleOkToSet();
        }
        this.variable_close()
      },
      variable_handleOkToSet(positionName, positionId) {
        if (this.variable.name) {
          this.variable.name = this.$t('m.bpm.other.showVariable')+'#' + this.variable_type + "#" + this.variable.name

          if (positionName && positionId) {
            this.variable.name += ("#" + positionName + "#" + positionId)
          }
        }
      },
      variable_handleCancel() {
        this.variable.name = null
        this.variable_close()
      },
      variable_close() {
        this.variable_visible = false
        if (!this.variable.name) {
          const data = this.value.filter(vo => vo.id != 'variable')
          this.$emit('input', data)
        }
      }
    }
  }
</script>
